#include "loomserver.h"

///
void runServer(void *arg) {
    thread_arg_t *thArg = (thread_arg_t*)arg;
    if (thArg->type == 2)
    {
        init_company_attr(g_mysql_conn, &g_companyattr);
        thArg->rserver->data = (void*)g_companyattr;
        if ( tcp4_server_main(thArg->port, thArg->loop, thArg->rserver)) {
            fprintf(stderr, "tcp4 server start at point %d error!\n", thArg->port);
            _exit(-1);
        }
        else {
            uv_run(thArg->loop, UV_RUN_DEFAULT);
        }
    }
    else
    {
	//TODO
    }
}

void startDBProcess(void *arg) {
    g_mysql_conn = mysql_init(NULL);
    ASSERT(g_mysql_conn != NULL);
    const char *reConnectFlag = "1";
    const char *charsetName = "utf8";
    int optRs = mysql_options(g_mysql_conn, MYSQL_OPT_RECONNECT, reConnectFlag);
    optRs = mysql_options(g_mysql_conn, MYSQL_SET_CHARSET_NAME, charsetName);

    MYSQL *ret = mysql_real_connect(g_mysql_conn, "localhost", "html5test", "html5test", "netloomsite", 0, "/tmp/mysql5.6.sock", 0);
    if (ret == NULL) {
        printf("mysql connected error!\n");
        exit(-1);
    }
}

int main(int argc, char *argv[])
{
    //if (fork() != 0) exit(0); /* parent exits */
    //setsid(); /* create a new session */
    uv_thread_t dataTId;
    thread_arg_t dataArg;
    uv_tcp_t dataServer;

    int tcpport     = 5000;
    //int statusport  = 8080;
    //connect mysql;
    startDBProcess((void*)NULL);

    //statusArg.port = statusport;
    //statusArg.type = 1; //HTTP STATUS
    //statusArg.loop = uv_loop_new();
    //statusArg.rserver = &statusServer;

    dataArg.port = tcpport;
    dataArg.type = 2;//TCPDATASTATUS
    dataArg.loop = uv_loop_new();
    dataArg.rserver = &dataServer;

    uv_thread_create(&dataTId,   runServer, (void*)&dataArg);

    printf("data thread id=%u\n", (uint32_t)dataTId);

    uv_thread_join(&dataTId);
    uv_loop_delete(dataArg.loop);

    mysql_close(g_mysql_conn);
    return 0;
}
